using System;
using NLog;

namespace TeamCityConfigurationMonitor.Core
{
    public class ConfigurationMonitor : IDisposable
    {
        private readonly ChangeNotifier watcher;
        private readonly Synchronizer synchronizer;
        private readonly Logger logger = LogManager.GetCurrentClassLogger();

        public ConfigurationMonitor(IConfiguration configuration)
        {
            var changeProvider = new ChangeProvider();
            watcher = new ChangeNotifier(configuration, OnConfigurationChange, changeProvider);
            synchronizer = new Synchronizer(configuration, changeProvider, watcher);
        }

        private void OnConfigurationChange()
        {
            synchronizer.Synchronize();
        }

        public void Start()
        {
            logger.Info("Starting");
            synchronizer.Synchronize();
            watcher.StartWatching();
        }

        public void Dispose()
        {
            logger.Info("Shutting down");
            watcher.Dispose();
            synchronizer.Dispose();
        }
    }
}